import { Book } from '../model/book.js'
import { Op } from 'sequelize'

let fn_list = async (ctx, next) => {
    const page = +ctx.query.page || 1
    const limit = +ctx.query.limit || 10
    const keyword = ctx.query.keyword?.trim() || ''

    const whereClause = keyword ? {
        [Op.or]: [
            { bookName: { [Op.like]: `%${keyword}%` } },
            { author: { [Op.like]: `%${keyword}%` } },
            { descriptions: { [Op.like]: `%${keyword}%` } }
        ]
    } : {}

    const { count, rows: books } = await Book.findAndCountAll({
        where: whereClause,
        offset: (page - 1) * limit,
        limit: limit
    });


    const totalPages = Math.ceil(count / limit);
    const visiblePages = 10

    let startPage = Math.max(1, page - Math.floor(visiblePages / 2))
    let endPage = startPage + visiblePages - 1

    if (endPage > totalPages) {
        endPage = totalPages;
        startPage = Math.max(1, endPage - visiblePages + 1);
    }

    ctx.render('books.html', {
        books,
        keyword,
        page,
        totalPages,
        limit,
        totalPages,
        startPage,
        endPage
    })
}

let fn_getById = async (ctx, next) => {
    let id = ctx.params.id || 0
    let books = await Book.findByPk(id)

    ctx.render('booksAddOrEdit.html', { books })
}


let fn_add = async (ctx, next) => {
    let id = ctx.request.qu
    let obj = ctx.request.body
    await Book.create(obj)
    ctx.body = '添加成功'
}

let fn_update = async (ctx, next) => {
    let id = ctx.params.id || 0;
    let book = await Book.findByPk(id);
    if (!book) {
        ctx.body = '要修改的图书不存在'
    } else {
        let obj = ctx.request.body

        await Book.update(obj, {
            where: {
                id: id
            }
        });

        ctx.body = '修改成功'
    }

}

let fn_delete = async (ctx, next) => {
    let id = ctx.params.id || 0;
    let book = await Book.findByPk(id);

    if (!book) {
        ctx.body = '要删除的图书不存在'
    } else {
        await Book.destroy({
            where: {
                id: id
            }
        })

        ctx.body = '删除成功'
    }


}

let fn_toAdd = async (ctx) => {
    ctx.render('booksAddOrEdit.html', {})
}

export const obj = {
    'get /books': fn_list,
    'get /books/:id': fn_getById,
    'post /books': fn_add,
    'put /books/:id': fn_update,
    'delete /books/:id': fn_delete,
    'get /add': fn_toAdd
}
